package com.marvinlabs.widget.slideshow.adapter;

import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.InputStream;
import java.util.Collection;

/**
 * A GenericBitmapAdapter that loads images from application resources.
 * <p/>
 * Created by Vincent Mimoun-Prat @ MarvinLabs on 29/05/2014.
 */
public abstract class GenericResourceBitmapAdapter<T> extends GenericBitmapAdapter<T> {

    // The options to pass to the BitmapFactory used to decode the bitmaps
    private ImageSource.DecodingOptions bitmapFactoryOptions;

    //==============================================================================================
    // GENERAL METHODS
    //==

    /**
     * Constructor
     *
     * @param context The context in which the adapter is created
     * @param items The items for which we have images to load
     */
    public GenericResourceBitmapAdapter(Context context, Collection<T> items) {
        super(context, items);
    }

    /**
     * Constructor
     *
     * @param context The context in which the adapter is created
     * @param items The items for which we have images to load
     * @param bitmapFactoryOptions The options to pass to the BitmapFactory used to decode the
     * bitmaps
     */
    public GenericResourceBitmapAdapter(Context context, Collection<T> items, ImageSource.DecodingOptions bitmapFactoryOptions) {
        super(context, items);
        this.bitmapFactoryOptions = bitmapFactoryOptions;
    }

    //==============================================================================================
    // ASYNC MANAGEMENT METHODS
    //==

    protected abstract int getItemImageResourceId(T item, int position);

    @Override
    protected PixelMap asyncLoadBitmap(T item, int position) {
        PixelMap bm = getPixelMap(getItemImageResourceId(item, position), bitmapFactoryOptions);
        return bm;
    }

    /**
     * 通过资源ID获取位图对象
     *
     * @param resId
     * @param decodingOptions
     * @return PixelMap
     */
    private PixelMap getPixelMap(int resId, ImageSource.DecodingOptions decodingOptions) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = getContext().getResourceManager().getResource(resId);
            ImageSource imageSource = ImageSource.create(drawableInputStream, null);
            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
            return pixelMap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
